<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name" label-width="90px">
        <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="部门/网点" prop="deptId" label-width="90px">
        <treeselect style="width: 210px" v-model="queryParams.deptId" :options="deptOptions" :normalizer="normalizer"
          placeholder="选择部门" />
      </el-form-item>
      <el-form-item label="描述" prop="info">
        <el-input v-model="queryParams.info" placeholder="请输入描述" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <br>
      <el-form-item label="当前处理人" prop="assignedUserId" label-width="90px">
        <el-input v-model="queryParams.assignedUserId" placeholder="请输入当前处理人" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="最终解决人" prop="troubleshootUserId" label-width="90px">
        <el-input v-model="queryParams.troubleshootUserId" placeholder="请输入最终解决人" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:workOrder:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:workOrder:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete"
          v-hasPermi="['system:workOrder:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:workOrder:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="true" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="部门/网点" align="center" prop="deptName" />
      <el-table-column label="描述" align="center" prop="info" />
      <el-table-column label="当前处理人" align="center" prop="assignedUserId" />
      <!-- <el-table-column label="最终解决人" align="center" prop="troubleshootUserId" /> -->
      <el-table-column label="工单图片" align="center" prop="ossUrls" width="180">
        <template slot-scope="scope">
          <ImagePreview v-if="previewListResource" :width=100 :height=100 :src="scope.row.ossUrls"
            :preview-src-list="[scope.row.ossUrls]" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="stautus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ic_work_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="处理完成时间" align="center" prop="completionTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.completionTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="最终耗时" align="center" prop="elapsedTime" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDispose(scope.row)">处理</el-button>
          <el-button size="mini" type="text" @click="handleAssign(scope.row)">指派</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:workOrder:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:workOrder:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 工单处理 -->
    <el-dialog :title="title" :visible.sync="openDispose" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="部门/网点" prop="deptId" label-width="73px" style="white-space: nowrap;">
          <treeselect style="margin-left: 7px; " v-model="form.deptId" :options="deptOptions" :normalizer="normalizer" placeholder="选择部门" />
        </el-form-item>
        <el-form-item label="描述" prop="info">
          <el-input v-model="form.info" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传工单图片" prop="ossIds">
          <div class="image-upload-container">
            <imageUpload v-model="form.ossIds" :fileType="['png', 'jpg']" :fileSize="30" style="width: 355px;" />
          </div>
        </el-form-item>
        <el-form-item label="处理人" prop="troubleshootUserId">
          <el-select v-model="form.assignedUserId" placeholder="请输入当前处理人">
            <el-option v-for="(item, index) in this.getassignedUserIdlist" :key="index" :label="item.userName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择工单状态">
            <el-option
              v-for="dict in dict.type.ic_work_order_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitDispose">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 工单指派-->
    <el-dialog :title="title" :visible.sync="openAssign" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <span>{{ form.name }}</span>
        </el-form-item>
        <el-form-item label="部门id" prop="deptId">
          <span>{{ form.deptId }}</span>
        </el-form-item>
        <el-form-item label="描述" prop="info">
          <span>{{ form.info }}</span>
        </el-form-item>
        <el-form-item label="当前处理人" prop="assignedUserId">
          <span>{{ form.assignedUserId }}</span>
        </el-form-item>
        <el-form-item label="新指派的处理人" prop="troubleshootUserId">
          <template>
            <el-select v-model="form.id" placeholder="请选择">
              <el-option v-for="item in workIds" :key="item.id" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="工单图片" prop="ossUrls">
          <img :src="getFirstImageUrl(form.ossUrls)" alt="资源图片" style="max-width: 100px; max-height: 100px;">
        </el-form-item>
        <!-- <el-form-item label="处理完成时间" prop="completionTime">
          <span>{{ form.completionTime }}</span>
        </el-form-item>
        <el-form-item label="最终耗时" prop="elapsedTime">
          <span>{{ form.elapsedTime }}</span>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitAssign">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改工单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="部门/网点" prop="deptId" label-width="73px" style="white-space: nowrap;">
          <treeselect style="margin-left: 7px; " v-model="form.deptId" :options="deptOptions" :normalizer="normalizer" placeholder="选择部门" />
        </el-form-item>
        <el-form-item label="描述" prop="info">
          <el-input v-model="form.info" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="当前处理人" prop="assignedUserId">
          <el-select v-model="form.assignedUserId" placeholder="请输入当前处理人">
            <el-option v-for="(item, index) in this.getassignedUserIdlist" :key="index" :label="item.userName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="最终解决人" prop="troubleshootUserId">
          <el-input v-model="form.troubleshootUserId" placeholder="请输入最终解决人" />
        </el-form-item> -->
        <el-form-item label="上传工单图片" prop="ossIds">
          <div class="image-upload-container">
            <imageUpload v-model="form.ossIds" :fileType="['png', 'jpg']" :fileSize="30" style="width: 355px;" />
          </div>
        </el-form-item>

        <!-- <el-form-item label="处理完成时间" prop="completionTime">
          <el-date-picker clearable v-model="form.completionTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择处理完成时间">
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="最终耗时" prop="elapsedTime">
          <el-input v-model="form.elapsedTime" placeholder="请输入最终耗时" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser } from "@/api/system/user";
import { listWorkOrder, getWorkOrder, delWorkOrder, addWorkOrder, updateWorkOrder, assignWorkOrder, disposeWorkOrder } from "@/api/system/workOrder";
import { listDept, getDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "WorkOrder",
  components: { Treeselect },
  dicts: ['ic_work_order_status'],
  data() {
    return {
      getassignedUserIdlist: null,
      // 预览列表图片
      previewListResource: true,
      // 预览的数据
      previewData: undefined,
      troubleshootUserId: null,
      status: null,
      //新指派处理人
      workIds: [],
      isShowDetail: false,
      isImagePreviewOpen: false,
      isShowDispose: false,
      // 视频和图片预览
      previewImageUrl: null,
      detailName: null,
      info: null,
      assignedUserId: null,
      assign: {
        id: null,
        troubleshootUserId: null
      },
      // 部门树形数据
      deptOptions: [],
      authOptions: [
        { label: "未授权", value: 2 },
        { label: "已授权", value: 1 }
      ],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单表格数据
      workOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openAssign: false,
      openDispose: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        deptId: undefined,
        status: undefined,
        info: undefined,
        assignedUserId: undefined,
        troubleshootUserId: undefined,
        ossIds: undefined,
        completionTime: undefined,
        elapsedTime: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "id不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "部门id不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        info: [
          { required: true, message: "描述不能为空", trigger: "blur" }
        ],
        assignedUserId: [
          { required: true, message: "当前处理人不能为空", trigger: "blur" }
        ],
        troubleshootUserId: [
          { required: true, message: "最终解决人不能为空", trigger: "blur" }
        ],
        ossIds: [
          { required: true, message: "描述资源图片组不能为空", trigger: "blur" }
        ],
        completionTime: [
          { required: true, message: "处理完成时间不能为空", trigger: "blur" }
        ],
        elapsedTime: [
          { required: true, message: "最终耗时不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getDeptList();

  },
  methods: {
    getFirstImageUrl(ossUrls) {
      if (ossUrls) {
        const urlArray = ossUrls.split(",");
        return urlArray.length > 0 ? urlArray[0] : ''; // 获取第一个图片链接
      }
      return ''; // 处理没有图片链接的情况
    },
    submitDispose() {
      this.form.workId = this.form.id;
      delete this.form.id;
      disposeWorkOrder(this.form).then(response => {
        this.$modal.msgSuccess("处理成功");
        this.getList();
        this.openDispose = false;
      }).finally(() => {
        this.openDispose = false;
      });
    },
    submitAssign() {
      this.assign.id = this.form.id;
      assignWorkOrder(this.assign).then(response => {
        this.$modal.msgSuccess("指派成功");
        this.getList();
        this.openAssign = false;
      }).finally(() => {
        this.openAssign = false;
      });
    },
    /** 查询部门列表 */
    getDeptList() {
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "deptId");
        console.log(this.deptOptions);
      });
      listUser().then((response) => {
        this.getassignedUserIdlist = response.rows.map(item => ({ userName: item.userName, userId: item.userId }));
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    /** 查询工单列表 */
    getList() {
      this.loading = true;
      listWorkOrder(this.queryParams).then(response => {
        console.log(response);
        this.workOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openAssign = false;
      this.openDispose = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        id: undefined,
        name: undefined,
        deptId: undefined,
        status: undefined,
        info: undefined,
        assignedUserId: undefined,
        troubleshootUserId: undefined,
        ossIds: undefined,
        completionTime: undefined,
        elapsedTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工单";
    },
    /** 工单处理按钮操作 */
    handleDispose(row) {
      this.reset();
      const id = row.id || this.ids
      getWorkOrder(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.openDispose = true;
        this.title = "处理工单";
      });
    },
    /** 工单指派按钮操作 */
    handleAssign(row) {
      this.assign.troubleshootUserId = row.troubleshootUserId;
      this.reset();
      for (var i = 0; i < this.workOrderList.length; i++) {
        var currentId = this.workOrderList[i].id;
        // 检查是否已经存在相同的id，如果不存在才添加到数组
        if (!this.workIds.some(item => item.id === currentId)) {
          this.workIds.push({ id: currentId });
        }
      }
      const id = row.id || this.ids
      getWorkOrder(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.openAssign = true;
        this.title = "工单指派";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getWorkOrder(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改工单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateWorkOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addWorkOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工单编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delWorkOrder(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/workOrder/export', {
        ...this.queryParams
      }, `workOrder_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>


